<template>
  <div class="content-area">
    <!-- 欢迎卡片 -->
    <div class="welcome-card">
      <div class="welcome-title">您好，{{ username }}管理员！</div>
      <div class="welcome-subtitle">
        今日系统运行正常，共有{{ todayStats.pendingRequests }}条待处理申请
      </div>
    </div>

    <!-- 数据概览卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-header">
          <div class="stat-title">科室数量</div>
          <div class="stat-icon">
            <el-icon><OfficeBuilding /></el-icon>
          </div>
        </div>
        <div class="stat-value">{{ overviewData.departments }}</div>
        <div class="stat-desc">较上月增加{{ overviewData.departmentIncrease }}个</div>
      </div>

      <div class="stat-card">
        <div class="stat-header">
          <div class="stat-title">医生总数</div>
          <div class="stat-icon">
            <el-icon><User /></el-icon>
          </div>
        </div>
        <div class="stat-value">{{ overviewData.doctors }}</div>
        <div class="stat-desc">在职医生{{ overviewData.activeDoctors }}人</div>
      </div>
      <div class="stat-card">
        <div class="stat-header">
          <div class="stat-title">护士总数</div>
          <div class="stat-icon">
            <el-icon><User /></el-icon>
          </div>
        </div>
        <div class="stat-value">{{ overviewData.nurses }}</div>
        <div class="stat-desc">在职护士{{ overviewData.activeNurses }}人</div>
      </div>
      <div class="stat-card">
        <div class="stat-header">
          <div class="stat-title">药剂师总数</div>
          <div class="stat-icon">
            <el-icon><User /></el-icon>
          </div>
        </div>
        <div class="stat-value">{{ overviewData.nurses }}</div>
        <div class="stat-desc">在职药剂师{{ overviewData.activeNurses }}人</div>
      </div>
      <div class="stat-card">
        <div class="stat-header">
          <div class="stat-title">患者总数</div>
          <div class="stat-icon">
            <el-icon><User /></el-icon>
          </div>
        </div>
        <div class="stat-value">{{ formatNumber(overviewData.patients) }}</div>
        <div class="stat-desc">本月新增{{ overviewData.newPatients }}人</div>
      </div>

      <div class="stat-card">
        <div class="stat-header">
          <div class="stat-title">今日挂号</div>
          <div class="stat-icon">
            <el-icon><Calendar /></el-icon>
          </div>
        </div>
        <div class="stat-value">{{ overviewData.todayAppointments }}</div>
        <div class="stat-desc">已完成{{ overviewData.completedAppointments }}个</div>
      </div>
    </div>

    <div class="main-content-grid">
      <!-- 左侧内容区域 -->
      <div class="left-content">
        <!-- 快捷操作区域 -->
        <div class="quick-actions">
          <div class="section-title">
            <span>快捷操作</span>
          </div>
          <div class="actions-grid">
            <div class="action-card" @click="navigateTo('department')">
              <div class="action-icon">
                <el-icon><OfficeBuilding /></el-icon>
              </div>
              <div class="action-title">科室管理</div>
              <div class="action-desc">管理医院科室信息</div>
            </div>

            <div class="action-card" @click="navigateTo('doctor')">
              <div class="action-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="action-title">医生管理</div>
              <div class="action-desc">管理医生信息与权限</div>
            </div>

            <div class="action-card" @click="navigateTo('nurse')">
              <div class="action-icon">
                <el-icon><FirstAidKit /></el-icon>
              </div>
              <div class="action-title">护士管理</div>
              <div class="action-desc">管理护士信息</div>
            </div>

            <div class="action-card" @click="navigateTo('pharmacist')">
              <div class="action-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="action-title">药剂师管理</div>
              <div class="action-desc">管理药剂师信息</div>
            </div>

            <div class="action-card" @click="navigateTo('schedule-templates')">
              <div class="action-icon">
                <el-icon><Calendar /></el-icon>
              </div>
              <div class="action-title">排班模板管理</div>
              <div class="action-desc">设置人员值班模板</div>
            </div>
            <div class="action-card" @click="navigateTo('schedule-instances')">
              <div class="action-icon">
                <el-icon><Calendar /></el-icon>
              </div>
              <div class="action-title">排班管理</div>
              <div class="action-desc">安排医护人员值班表</div>
            </div>

            <div class="action-card" @click="navigateTo('medicine')">
              <div class="action-icon">
                <el-icon><Box /></el-icon>
              </div>
              <div class="action-title">药品管理</div>
              <div class="action-desc">管理药品信息</div>
            </div>

            <div class="action-card" @click="navigateTo('billing')">
              <div class="action-icon">
                <el-icon><Coin /></el-icon>
              </div>
              <div class="action-title">收费管理</div>
              <div class="action-desc">管理收费记录</div>
            </div>

            
          </div>
        </div>

        <!-- 待处理事务 -->
        <div class="pending-tasks">
          <div class="section-title">
            <span>待处理事务</span>
            <span class="view-all" @click="navigateTo('pending-tasks')">查看全部</span>
          </div>

          <div class="task-list">
            <div 
              v-for="task in pendingTasks" 
              :key="task.id" 
              class="task-item"
              @click="handleTaskAction(task)"
            >
              <div class="task-info">
                <div class="task-title">{{ task.title }}</div>
                <div class="task-desc">{{ task.description }}</div>
                <div class="task-time">{{ task.time }}</div>
              </div>
              <div class="task-actions">
                <el-button size="small" type="primary">{{ task.actionText }}</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="right-content">
        <!-- 系统状态 -->
        <div class="system-status">
          <div class="section-title">
            <span>系统状态</span>
          </div>

          <div class="status-cards">
            <div class="status-card">
              <div class="status-title">CPU使用率</div>
              <div class="status-value">{{ systemStatus.cpu }}%</div>
              <el-progress
                :percentage="systemStatus.cpu"
                :color="getProgressColor(systemStatus.cpu)"
                :show-text="false"
              ></el-progress>
            </div>

            <div class="status-card">
              <div class="status-title">内存使用率</div>
              <div class="status-value">{{ systemStatus.memory }}%</div>
              <el-progress
                :percentage="systemStatus.memory"
                :color="getProgressColor(systemStatus.memory)"
                :show-text="false"
              ></el-progress>
            </div>

            <div class="status-card">
              <div class="status-title">磁盘使用率</div>
              <div class="status-value">{{ systemStatus.disk }}%</div>
              <el-progress
                :percentage="systemStatus.disk"
                :color="getProgressColor(systemStatus.disk)"
                :show-text="false"
              ></el-progress>
            </div>
          </div>
        </div>

        <!-- 最近活动 -->
        <div class="recent-activities">
          <div class="section-title">
            <span>最近活动</span>
            <span class="view-all" @click="navigateTo('activities')">查看全部</span>
          </div>

          <div class="activity-list">
            <div 
              v-for="activity in recentActivities" 
              :key="activity.id" 
              class="activity-item"
            >
              <div class="activity-icon">
                <el-icon><component :is="activity.icon" /></el-icon>
              </div>
              <div class="activity-content">
                <div class="activity-title">{{ activity.title }}</div>
                <div class="activity-time">{{ activity.time }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import {
  ElMessage,
  ElIcon,
  ElButton,
  ElProgress,
} from "element-plus";
// ============引入后端API接口=============
import { getHomeStatsData } from "@/api/api";

const router = useRouter();
const store = useStore();

const username = ref(store.state.user?.username || "管理员");

// 响应式数据
const todayStats = ref({
  pendingRequests: 0
});

// 概览数据
const overviewData = ref({
  departments: 0,
  departmentIncrease: 0,
  doctors: 0,
  activeDoctors: 0,
  nurses: 0,
  activeNurses: 0,
  pharmacists: 0,
  activePharmacists: 0,
  patients: 0,
  newPatients: 0,
  todayAppointments: 0,
  completedAppointments: 0
});

const systemStatus = ref({
  cpu: 0,
  memory: 0,
  disk: 0,
  visits: 0,
  visitTrend: 0
});

// 加载首页统计数据
const fetchDashboardData = async () => {
  try {
    const response = await getHomeStatsData();
    if (response && response.code == 200) {
      const data = response.data;
      overviewData.value = {
        departments: data.departmentCount|| 0,
        departmentIncrease: data.newDepartmentThisMonth || 0,
        doctors: data.doctorCount|| 0,
        activeDoctors: data.activeDoctors|| 0,
        nurses: data.nurseCount|| 0,
        activeNurses: data.activeNurses|| 0,
        pharmacists: data.pharmacistCount|| 0,
        activePharmacists: data.activePharmacists|| 0,
        patients: data.patientCount|| 0,
        newPatients: data.newPatientsThisMonth|| 0,
        todayAppointments: data.todayAppointments|| 0,
        completedAppointments: data.completedAppointments|| 0
      };
      systemStatus.value = {
        cpu: data.cpuUsage || 0,
        memory: data.memoryUsage || 0,
        disk: data.diskUsage || 0,
        visits: data.todayVisits || 0,
        visitTrend: data.visitTrend || 0
      };
      todayStats.value.pendingRequests = data.pendingRequests|| 0;
      ElMessage.success("首页统计数据加载成功");
    }else{
      ElMessage.error(response.msg || "获取首页统计数据失败");
    }
  } catch (error) {
    ElMessage.error("获取首页统计数据失败");
    console.error("Error fetching dashboard data:", error);
  }
};

const pendingTasks = ref([
  {
    id: 1,
    title: "新医生注册申请",
    description: "李明医生提交了注册申请",
    time: "10分钟前",
    actionText: "审核",
    type: "doctor_approval"
  },
  {
    id: 2,
    title: "科室调整建议",
    description: "心血管内科请求增加诊室",
    time: "今天 09:30",
    actionText: "处理",
    type: "department_request"
  },
  {
    id: 3,
    title: "系统报警通知",
    description: "数据库存储空间不足警告",
    time: "昨天 17:45",
    actionText: "处理",
    type: "system_alert"
  }
]);

const recentActivities = ref([
  {
    id: 1,
    title: "新患者注册",
    time: "2分钟前",
    icon: "User"
  },
  {
    id: 2,
    title: "医生排班更新",
    time: "1小时前",
    icon: "Calendar"
  },
  {
    id: 3,
    title: "药品库存预警",
    time: "3小时前",
    icon: "Box"
  },
  {
    id: 4,
    title: "系统备份完成",
    time: "今天 08:00",
    icon: "Document"
  }
]);

const navigateTo = (page) => {
  router.push(`/manager/${page}`);
};

const handleTaskAction = (task) => {
  switch (task.type) {
    case 'doctor_approval':
      navigateTo('doctor');
      break;
    case 'department_request':
      navigateTo('department');
      break;
    case 'system_alert':
      ElMessage.warning('正在处理系统报警...');
      break;
    default:
      ElMessage.info(`处理任务: ${task.title}`);
  }
};

const formatNumber = (num) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

const getProgressColor = (percentage) => {
  if (percentage < 50) return "#1a75bc";
  if (percentage < 80) return "#e6a23c";
  return "#f56c6c";
};

// 模拟获取初始数据
onMounted(() => {
  // 这里可以添加获取初始化数据的逻辑
  fetchDashboardData();
});
</script>

<style lang="scss" scoped>
/* 主内容区域样式 */
.content-area {
  flex: 1;
  padding: 24px;
  background-color: #f5f7fa;
  height: 0;  // 添加这行
  min-height: 100%;  // 添加这行
  overflow-y: auto;  // 确保有这行
}

.welcome-card {
  background: linear-gradient(135deg, #1a75bc 0%, #0c4d8c 100%);
  border-radius: 12px;
  padding: 24px;
  color: white;
  margin-bottom: 24px;
}

.welcome-title {
  font-size: 24px;
  margin-bottom: 8px;
}

.welcome-subtitle {
  opacity: 0.9;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  }
}

.stat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.stat-title {
  font-size: 16px;
  color: #606266;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(26, 117, 188, 0.1);
  color: #1a75bc;
}

.stat-value {
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 4px;
}

.stat-desc {
  color: #909399;
  font-size: 14px;
}

/* 主内容网格布局 */
.main-content-grid {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
}

.left-content, .right-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.quick-actions {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 18px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
}

.view-all {
  color: #1a75bc;
  font-size: 14px;
  cursor: pointer;
  font-weight: normal;
  transition: color 0.3s;

  &:hover {
    color: #0c4d8c;
  }
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.action-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    border-color: #1a75bc;
    box-shadow: 0 4px 12px rgba(26, 117, 188, 0.1);
    transform: translateY(-2px);
  }
}

.action-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: rgba(26, 117, 188, 0.1);
  color: #1a75bc;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 12px;

  .el-icon {
    font-size: 24px;
  }
}

.action-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.action-desc {
  color: #909399;
  font-size: 12px;
}

.pending-tasks,
.system-status,
.recent-activities {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.task-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.task-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    border-color: #1a75bc;
    box-shadow: 0 2px 8px rgba(26, 117, 188, 0.1);
  }
}

.task-info {
  flex: 1;
}

.task-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.task-desc {
  color: #606266;
  font-size: 14px;
  margin-bottom: 4px;
}

.task-time {
  color: #909399;
  font-size: 12px;
}

.status-cards {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
}

.status-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 16px;
}

.status-title {
  color: #606266;
  margin-bottom: 8px;
}

.status-value {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
}

.status-desc {
  font-size: 12px;
  
  &.positive {
    color: #67c23a;
  }
  
  &.negative {
    color: #f56c6c;
  }
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.activity-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  transition: all 0.3s;

  &:hover {
    border-color: #1a75bc;
    box-shadow: 0 2px 8px rgba(26, 117, 188, 0.1);
  }
}

.activity-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: rgba(26, 117, 188, 0.1);
  color: #1a75bc;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;

  .el-icon {
    font-size: 16px;
  }
}

.activity-content {
  flex: 1;
}

.activity-title {
  font-weight: 500;
  margin-bottom: 4px;
}

.activity-time {
  color: #909399;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content-grid {
    grid-template-columns: 1fr;
  }
  
  .actions-grid {
    grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  }
}

@media (max-width: 768px) {
  .content-area {
    padding: 16px;
  }
  
  .stats-cards {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
  }
  
  .actions-grid {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 12px;
  }
  
  .main-content-grid {
    gap: 16px;
  }
}
</style>